package com.tinygray.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *  要求：
 *      A执行完调用B，B执行完调用C，C执行完调用A。
 */
public class pc2 {
    public static void main(String[] args) {
        Data2 data2 = new Data2();
        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                data2.printA();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                data2.printB();
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                data2.printC();
            }
        },"C").start();
    }
}

/**
 * 资源类
 */
class Data2 {
    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();
    private int number = 1; //1A 2B 3C
    public void printA(){
        lock.lock();
        try {
            /**
             *  业务：
             *      判断是否等待过程---> 执行 ----> 通知
             */
            while (number != 1) {
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName() + "===>AAA");
            number = 2;
            //指定唤醒的人  ---> B
            condition2.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void printB(){
        lock.lock();
        try {
            while (number != 2) {
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName() + "===>BBB");
            number = 3;
            //换性指定的人 ---> C
            condition3.signalAll();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        lock.lock();
        try {
            while (number != 3) {
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName() + "===>CCC");
            number = 1;
            //唤醒指定的人 --->A
            condition1.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

